import HttpClient from '../commons/http-client';
import {resetRegisterForm, updateRegisterForm} from '../reducers/register-form';
import {FormStatus, updateAppState} from '../reducers/app-state';
import {fetchUserInfo, login} from './auth-actions';
import {UserType} from '../reducers/user';
import {NavigationActions, StackActions} from 'react-navigation';
import _ from 'lodash';

export function submitRegister(form) {
  return async (dispatch, getState) => {
    const {registerForm} = getState();
    try {
      dispatch(updateAppState({formStatus: FormStatus.PENDING}));
      const url = [UserType.dentist, UserType.clinic].includes(
        registerForm.role,
      )
        ? '/web/dentist/new'
        : '/web/vendor/new';
      const regRep = await HttpClient.post(url, {
        ...form,
        type: registerForm.role,
        verify: form.captcha,
      });
      dispatch(updateRegisterForm(regRep.data.data));
      await dispatch(login({username: form.email, password: form.password}));
      dispatch(updateAppState({formStatus: FormStatus.SUCCESS}));
    } catch (e) {
      dispatch(updateAppState({formStatus: FormStatus.FAIL}));
      throw e;
    }
  };
}

export function submitCert(form, user) {
  return async dispatch => {
    const info = {
      hold_card: form.cert ? form.cert.id : null,
      address_1: form.address_1,
      tel: form.tel,
      country: form.country,
      province: form.province,
      city: form.city,
      district: form.district,
      address_2: form.address_2,
      longitude: form.longitude,
      latitude: form.latitude,
      wechat: form.wechat,
      whatsapp: form.whatsapp,
      facebook: form.facebook,
    };
    let params = {};
    if ([UserType.technician, UserType.provider].includes(form.role)) {
      params.info = {
        ...info,
        vendor_name: form.name || form.email,
      };
      params.products = {
        fixed_products: Object.values(form.fixed || {}).filter(
          product => product.enabled,
        ),
        remv_arch_products: Object.values(form.remvArch || {}).filter(
          product => product.enabled,
        ),
      };
    } else {
      info.clinic_name = form.name || form.email;
      params = {...info};
    }
    try {
      dispatch(updateAppState({formStatus: FormStatus.PENDING}));
      const url = `/web/${
        [UserType.dentist, UserType.clinic].includes(form.role)
          ? 'dentist'
          : 'vendor'
      }/${user.id}/authorize`;
      await HttpClient.post(url, params);
      dispatch(fetchUserInfo());
      // dispatch(StackActions.popToTop());
      dispatch(NavigationActions.navigate({routeName: 'Main'}));
      dispatch(resetRegisterForm());
      dispatch(updateAppState({formStatus: FormStatus.SUCCESS}));
    } catch (e) {
      dispatch(updateAppState({formStatus: FormStatus.FAIL}));
      throw e;
    }
  };
}

export function sendCaptcha(email) {
  return async dispatch => {
    const codeRep = await HttpClient.post('/web/send-email-code', {email});
    const code = _.get(codeRep, 'data.data.code');
    dispatch(updateRegisterForm({code}));
  };
}

export function update(form) {
  return dispatch => {
    dispatch(updateRegisterForm(form));
  };
}

export function updateAddress(location) {
  return dispatch => {
    const payload = {
      latitude: location.latitude,
      longitude: location.longitude,
      address_1: location.address,
      country: location.country,
    };
    dispatch(updateRegisterForm(payload));
  };
}
